export default () => {
  class HomeCloud {
  //   constructor() { }

    save(data: string | Blob | Uint8Array, url: string) {
      return this.request('PUT', url, data)
    }

    load(url: string) {
      return this.request('GET', url)
    }

    async dirExist(url: string) {
      return await fetch(url, { 'method': 'PROPFIND' })
    }

    async createdir(url: string) {
      return await fetch(url, { 'method': 'MKCOL' })
    }

    async autoCreateDir(mymindDir: string) {
      const r = await this.dirExist(mymindDir)
      if (r.status === 207) {
        // console.log('exist mymindDir')
      }
      else {
        await this.createdir(mymindDir)
        // console.log('exist not mymindDir')
        // r = await this.createdir(mymindDir)
        // if (r.status === 201) {
        // console.log('create mymindDir success')
        // }
        // else {
        // console.log('create mymindDir failed')
        // }
      }
    }

    async request(method: string, url: string, data?: string | Blob | Uint8Array) {
      const init: RequestInit = {
        method,
        cache: 'no-cache',
        credentials: 'include'
      }
      if (data) {
        init.body = data
      }

      const response = await fetch(url, init)
      const text = await response.text()

      if (response.status === 201 || response.status === 200) {
        return text
      }
      throw new Error(`HTTP/${response.status}\n\n${text}`)
    }

    async fetch(method: string, url: string, data?: string | Blob | Uint8Array) {
      const init: RequestInit = {
        method,
        cache: 'no-cache',
        credentials: 'include'
      }
      if (data) {
        init.body = data
      }

      return await fetch(url, init)
    }
  }

  const saveToHomeCloud = async (data: any, WebDavFilePath: string, message:any) => {
    const cloud = new HomeCloud()
    const nowDate = (new Date()).toISOString().replace('T', '_').replace('Z', '').replace('-', '').replace('-', '').replace(':', '').replace(':', '').substring(0, 15)
    const extension = WebDavFilePath.split('.').pop()
    const baseName = WebDavFilePath.substring(0, WebDavFilePath.lastIndexOf('.'))
    // console.log(`${baseName}.${nowDate}.${extension}`)
    const res = await cloud.save(data, `${baseName}.${nowDate}.${extension}`)
    if (res === 'Created') {
      message.success(`导出到网盘成功。`)
    }
    else {
      message.error(`导出到网盘失败。`)
    }
  }

  const loadHomeCloud = async (url: string) => {
    const cloud = new HomeCloud()
    return await cloud.fetch('GET', url)
  }

  return {
    HomeCloud,
    saveToHomeCloud,
    loadHomeCloud,
  }
}